package com.example.component;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;

import java.util.Collection;

/*
 * 自定义RBAC验证，用于动态规划权限(url)
 */
@Component("rbacauthorityservice")
public class RBACAuthorityHandler {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    
    //动态判断当前用户是否具有访问当前url的权限
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        boolean hasPermission = false;
        
        Object principal = authentication.getPrincipal();
        
        if (principal instanceof UserDetails) {
        	
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for(GrantedAuthority grantedAuthority : authorities){
                if (antPathMatcher.match(grantedAuthority.getAuthority(), request.getRequestURI())) {
                    hasPermission = true;
                    break;
              }
            }
        }
        
        return hasPermission;
    }
}